package net.maku.kyy.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.maku.api.module.system.SmsApi;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.constant.MessageConstant;
import net.maku.framework.common.constant.RegexConstants;
import net.maku.framework.common.exception.ServerException;

import net.maku.framework.security.crypto.Sm2Util;
import net.maku.kyy.dao.KyyUserDao;
import net.maku.kyy.dto.KyySignDTO;
import net.maku.kyy.dto.KyyUserRegisterDTO;
import net.maku.kyy.entity.KyyUserEntity;
import net.maku.kyy.service.KyyUserRegisterService;
import net.maku.kyy.utils.GetUserMessageUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;

@Slf4j
@Service
public class KyyUserRegisterServiceImpl implements KyyUserRegisterService{

    @Autowired
    private KyyUserDao kyyUserDao;
    @Autowired
    private KyyUserLoginServiceImpl kyyUserLoginServiceImpl;

    @Autowired
    private SmsApi smsApi;

    /**
     * 注册
     * @param kyySignDTO
     */
    @Transactional
    @Override
    public void register(KyySignDTO kyySignDTO) {
        KyyUserRegisterDTO kyyUserRegisterDTO = kyySignDTO.getKyyUserRegisterDTO();
        String code = kyySignDTO.getCode();
        String phone = kyyUserRegisterDTO.getPhone();
        //非空判断
        if (phone == null){
            throw new ServerException(MessageConstant.PHONE_NOT_NULL);
        }
        //判断手机号格式
        validatePhone(phone);
        //System.out.println("验证验证码"+smsApi.verifyCode(phone,code));
        if(!smsApi.verifyCode("kyy:register:code:"+phone,code)){
            //log.error("Code error");
            throw new ServerException(MessageConstant.CODE_ERROR);//应该是响应到前端去了
        }
        //判断密码格式
        String password = kyyUserRegisterDTO.getPassword();
        validatePassword(password);
        //判断昵称
        String nickName = kyyUserRegisterDTO.getNickName();
        validateNickName(kyyUserRegisterDTO.getNickName());
        //判断性别
        Integer gender = kyyUserRegisterDTO.getGender();
        validateGender(kyyUserRegisterDTO.getGender());
        //加密密码
        String passwordEd=Sm2Util.encrypt(password);
        //随机生成一个10位的账号
        String account= GetUserMessageUtil.RandomAccount();
        KyyUserEntity kyyUserEntity = KyyUserEntity.builder()
                .nickName(nickName)
                .mobile(phone)
                .password(passwordEd)
                .gender(gender)
                .status(Constant.USER_STATUS_NORMAL) //默认用户状态正常
                .forumPermission(Long.valueOf(Constant.FORUM_PUBLISH_NORMAL_STR))//发布权限状态正常
                .account(account)
                .build();
        //将用户数据添加
        kyyUserDao.insert(kyyUserEntity);
        log.info(phone+"的用户注册成功");
    }

    /**
     * 生成随机账号
     * @return
     */
    @NotNull
    public static String getAccount() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }

    /**
     * 校验密码格式
     *
     * @param password 密码
     */
    private void validatePassword(String password) {
        log.info("Validating password format");
        if (!password.matches(RegexConstants.PASSWORD_REGEX)) {
            log.error("Invalid password format");
            throw new ServerException(MessageConstant.PASSWORD_FORMAT_ERROR);
        }
    }

    /**
     * 校验手机号
     *
     * @param phone 手机号
     */
    private void validatePhone(String phone) {
        log.info("Validating phone: {}", phone);
        if (kyyUserLoginServiceImpl.isExistPhone(phone)) {
            log.error("Phone {} already exists", phone);
            throw new ServerException(MessageConstant.PHONE_EXIST_REGISTER);
        }
        if (!phone.matches(RegexConstants.PHONE_REGEX)){
            throw new ServerException(MessageConstant.PHONE_FORMAT_ERROR);
        }
    }

    /**
     * 校验昵称
     *
     * @param nickName 昵称
     */
    private void validateNickName(String nickName) {
        log.info("Validating nickname: {}", nickName);
        if (nickName == null) {
            log.error("Nickname cannot be null");
            throw new ServerException(MessageConstant.NIKE_NAME_NOT_NULL);
        }
        if (nickName.length() > 12) {
            log.error("Nickname exceeds maximum length of 12 characters");
            throw new ServerException(MessageConstant.NIKE_NAME_NOT_OVER_12);
        }
    }

    /**
     * 校验性别
     *
     * @param gender 性别
     */
    private void validateGender(Integer gender) {
        log.info("Validating gender: {}", gender);
        if (gender == null) {
            log.error("Gender cannot be null");
            throw new ServerException(MessageConstant.GENDER_NOT_NULL);
        }
        if (!(gender == 0 || gender == 1 || gender == 2)) {
            log.error("Invalid gender value: {}", gender);
            throw new ServerException(MessageConstant.GENDER_ERROR);
        }
    }
}
